package com.eascs.web.o2o.web.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.UrlUtil;
import com.eascs.report.common.entity.BusiOperaForm;
import com.eascs.site.view.ViewContext;
import com.eascs.tag.MenuTag;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.web.o2o.web.entity.O2oPlatformRegional;
import com.eascs.web.o2o.web.service.BusiOperaService;
import com.eascs.web.o2o.web.service.ProvinceNameData;

/**
 * 业务运营分析（贷后数据）
 * 工单：report-10331
 * @author:hzp
 * @date:2018年3月14日
*/
@Controller
@RequestMapping("/report")
public class LoanAfterController extends BaseMasterViewController{
	private static Logger logger = LoggerFactory.getLogger(LoanAfterController.class);
	SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
	@Autowired
	ProvinceNameData provinceNameData;
	
	@Autowired
	BusiOperaService boService;

	/**
	 * 业务运营分析（贷后数据）首页
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/busiOperate4loanAfterIndex")
	public String ReportStatByProvince(BusiOperaForm entity) {
		logger.info("接口/report/busiOperate4loanAfterIndex入参:{}", JSON.toJSONString(entity));
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "business_operate_loanafter");
		String o2ourl = "/reportRest/busiOperate4loanAfter";	
		
		if (entity != null) {
			String loanDateStart = entity.getLoanDateStart() == null ? null : entity.getLoanDateStart();
			String loanDateEnd = entity.getLoanDateEnd() == null ? null : entity.getLoanDateEnd();
			String province = entity.getProvince() == null ? "" : entity.getProvince();
			String bankLoan = entity.getBankLoan() == null ? "" : entity.getBankLoan();
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanDateStart", loanDateStart);
			o2ourl = UrlUtil.appendUrl(o2ourl, "loanDateEnd", loanDateEnd);
			o2ourl = UrlUtil.appendUrl(o2ourl, "province", province);
			o2ourl = UrlUtil.appendUrl(o2ourl, "bankLoan", bankLoan);
			o2ourl = o2ourl + "&pageIndex=";
		} else {
			o2ourl = o2ourl + "?pageIndex=";
		}

		List<O2oPlatformRegional> proList = provinceNameData.getProvinceNameData();

		ViewContext.put("o2ourl", o2ourl);
		ViewContext.put("vo", entity);
		ViewContext.put("proList", proList);
		return "reportstat/busiOperate4loanAfter";
	}
	
	// 业务运营分析（贷后数据）报表下载
	@RequestMapping("/downloadBusiOperate")
	public void downloadProvince(BusiOperaForm entity, HttpServletResponse response,
	                             HttpServletRequest request) throws IOException{
		entity.setPageSize(10000);
		PageResult<Object[]> pageResult = boService.getLoanAfter(entity);
		String excelName="业务运营分析（贷后数据）";
	    HSSFWorkbook wb = new HSSFWorkbook();
	    HSSFSheet sheet = wb.createSheet();
	    HSSFRow row = sheet.createRow(0);
	    List<Object[]> data = pageResult.getData();
	    
	    HSSFDataFormat hdf = wb.createDataFormat();
	    HSSFCellStyle date_style = wb.createCellStyle();
	    date_style.setDataFormat(hdf.getFormat("yyyy-MM-dd"));;
	    
	    //2,创建表头
	    row.createCell(0).setCellValue("贷款申请单号");
	    row.createCell(1).setCellValue("省区");
	    row.createCell(2).setCellValue("区域总监");
	    row.createCell(3).setCellValue("信贷经理");
	    row.createCell(4).setCellValue("信贷经理入职时间");
	    row.createCell(5).setCellValue("放款银行");
	    row.createCell(6).setCellValue("贷款类型");
	    row.createCell(7).setCellValue("申请金额（万元）");
	    row.createCell(8).setCellValue("终审金额（万元）");
	    row.createCell(9).setCellValue("放款金额（万元）");
	    row.createCell(10).setCellValue("放款日期");
	    row.createCell(11).setCellValue("到期日期");
	    row.createCell(12).setCellValue("是否续贷");
	    row.createCell(13).setCellValue("借款人ID");
	    row.createCell(14).setCellValue("借款人姓名");
	    row.createCell(15).setCellValue("客户首次放款时间");
	    row.createCell(16).setCellValue("客户所在省份");
	    row.createCell(17).setCellValue("客户所在城市");
	    row.createCell(18).setCellValue("客户所在区县");
	    
	    //3,循环写入数据
	    for(int i=0;i<data.size();i++){
	    	row = sheet.createRow(i+1);
	    	Object[] o = data.get(i);
	    	row.createCell(0).setCellValue((String)o[0]);
	    	row.createCell(1).setCellValue((String)o[1]);
	    	row.createCell(2).setCellValue((String)o[2]);
	    	row.createCell(3).setCellValue((String)o[3]);
	    	row.createCell(4).setCellValue(o[4]!=null?((java.sql.Date)(o[4])).toString():"");
	    	row.createCell(5).setCellValue((String)o[5]);
	    	row.createCell(6).setCellValue((String)o[6]);
	    	row.createCell(7).setCellValue(((BigDecimal)o[7]).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
	    	row.createCell(8).setCellValue(((BigDecimal)o[8]).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
	    	row.createCell(9).setCellValue(((BigDecimal)o[9]).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
	    	row.createCell(10).setCellValue(sdf.format(o[10]));
	    	row.createCell(11).setCellValue(sdf.format(o[11]));
	    	row.createCell(12).setCellValue((String)o[12]);
	    	row.createCell(13).setCellValue((String)o[13]);
	    	row.createCell(14).setCellValue((String)o[14]);
	    	row.createCell(15).setCellValue(sdf.format(o[15]));
	    	row.createCell(16).setCellValue((String)o[16]);
	    	row.createCell(17).setCellValue((String)o[17]);
	    	row.createCell(18).setCellValue((String)o[18]);
	    }
	    
	    writeWbToResponse(response, excelName + ".xls", wb);		
		
	}	
	
	/**
	 * 将制作好的HSSFWorkbook写入response
	 * @param response
	 * @param fileName ，注意文件名后缀,xxx.xls
	 * @param wb
	 * @throws IOException
	 */
	private void writeWbToResponse(HttpServletResponse response , String fileName ,HSSFWorkbook wb) throws IOException{
		ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
 
        try {
          bis = new BufferedInputStream(is);
          bos = new BufferedOutputStream(out);
          byte[] buff = new byte[2048];
          int bytesRead;
          while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
        	  bos.write(buff, 0, bytesRead);
          }
         } catch (Exception e) {
            e.printStackTrace();
         } finally {
          if (bis != null)
              bis.close();
          if (bos != null)
              bos.close();
        }		
	}	
	public static void main(String[] args) {
		
	}
}
